<template>
  <a-config-provider :locale="zhCN" :theme="themeConfig">
    <div class="layout">
      <!-- 移动端提示 -->
      <div v-if="isMobileDevice" class="mobile-warning">
        <img src="@/assets/logo.png" alt="logo" style="width: 64px; height: 64px; margin-bottom: 20px" />
        <h2>未适配该型号设备</h2>
        <p>请使用PC端登录</p>
      </div>
      <template v-else-if="storeReady">
        <div class="header" :class="{ 'coffee-wall-bg': isCoffeeWallPage }">
          <div class="logo" @click="router.push('/')">
            <img src="@/assets/logo.png" alt="logo" style="width: 32px; height: 32px" />
            书签管理器
          </div>
          <div class="header-actions">
            <a-dropdown>
              <a-button type="link">
                <template #icon><tool-outlined /></template>
                工具箱
              </a-button>
              <template #overlay>
                <a-menu>
                  <a-menu-item v-for="item in toolMenuItems" :key="item.key" @click="handleToolClick(item.key)">
                    <component :is="item.icon" />
                    {{ item.label }}
                  </a-menu-item>
                </a-menu>
              </template>
            </a-dropdown>

            <a-button type="link" @click="openEcharts">
              <template #icon><bar-chart-outlined /></template>
              Echarts
            </a-button>

            <a-button type="link" @click="openFontManager">
              <template #icon><file-image-outlined /></template>
              图标库
            </a-button>
            <a-button type="link" @click="openIllustrationGallery">
              <template #icon><file-image-outlined /></template>
              插画库
            </a-button>

            <a-button type="link" @click="openWhiteboard">
              <template #icon><edit-outlined /></template>
              在线白板
            </a-button>

            <a-button type="link" @click="openArticles">
              <template #icon><file-text-outlined /></template>
              文章交流
            </a-button>

            <a-button type="link" @click="openCoffeeWall">
              <template #icon><coffee-outlined /></template>
              咖啡墙
            </a-button>

            <a-button type="link" @click="openFileStorage">
              <template #icon><folder-outlined /></template>
              文件存储
            </a-button>

            <!-- 用户管理（仅管理员可见） -->
            <a-button v-if="isAdmin" type="link" @click="openUserManagement">
              <template #icon><setting-outlined /></template>
              用户管理
            </a-button>

            <!-- 用户头像和登录状态 -->
            <a-dropdown v-if="userStore.isAuthenticated" trigger="click">
              <div style="position: relative; cursor: pointer; margin-left: 30px; display: inline-block">
                <a-avatar :size="46" :src="userStore.avatar ? getImageUrl(userStore.avatar) : ''" :style="{ fontSize: '18px' }">
                  {{ userStore.username?.charAt(0)?.toUpperCase() || 'U' }}
                </a-avatar>
                <span
                  v-if="unreadNotificationCount > 0"
                  style="
                    position: absolute;
                    bottom: -5px;
                    right: -5px;
                    background: #ff4d4f !important;
                    color: white !important;
                    padding: 2px 6px;
                    border-radius: 12px;
                    font-size: 12px;
                    min-width: 20px;
                    text-align: center;
                    border: 2px solid white;
                    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.3);
                    z-index: 1001;
                    font-weight: bold;
                    display: block;
                  "
                >
                  {{ unreadNotificationCount > 99 ? '99+' : unreadNotificationCount }}
                </span>
              </div>
              <template #overlay>
                <a-menu>
                  <a-menu-item key="profile" disabled>
                    <a-typography-text>{{ userStore.username }}</a-typography-text>
                    <br />
                    <a-typography-text type="secondary" style="font-size: 12px">{{ userStore.email }}</a-typography-text>
                  </a-menu-item>
                  <a-menu-divider />
                  <a-menu-item key="userCenter" @click="openUserCenter">
                    <template #icon><user-outlined /></template>
                    个人主页
                  </a-menu-item>
                  <a-menu-item key="myArticles" @click="openMyArticles">
                    <template #icon><file-text-outlined /></template>
                    我的文章
                  </a-menu-item>
                  <a-menu-item key="notifications" @click="openNotifications">
                    <template #icon><bell-outlined /></template>
                    <span style="display: flex; justify-content: space-between; align-items: center; width: 100%">
                      <span>消息通知</span>
                      <span
                        v-if="unreadNotificationCount > 0"
                        style="background: #ff4d4f !important; color: white !important; padding: 0px 6px; border-radius: 12px; font-size: 12px; min-width: 20px; text-align: center; font-weight: bold; display: inline-block; margin-left: 8px"
                      >
                        {{ unreadNotificationCount > 99 ? '99+' : unreadNotificationCount }}
                      </span>
                    </span>
                  </a-menu-item>
                  <a-menu-divider />
                  <a-menu-item key="changePassword" @click="openChangePasswordDialog">
                    <template #icon><lock-outlined /></template>
                    修改密码
                  </a-menu-item>
                  <a-menu-item key="logout" @click="handleLogout">
                    <template #icon><user-outlined /></template>
                    退出登录
                  </a-menu-item>
                </a-menu>
              </template>
            </a-dropdown>

            <!-- 未登录时显示登录按钮 -->
            <a-button type="link" v-else @click="openLoginDialog" style="margin-left: 30px">
              <template #icon><user-outlined /></template>
              登录
            </a-button>
          </div>
        </div>

        <div class="content">
          <router-view></router-view>
        </div>
        <div class="footer" :class="{ 'coffee-wall-bg': isCoffeeWallPage }">作者邮箱：<a href="mailto:524926126@qq.com">524926126@qq.com</a> 欢迎提意见改进</div>
      </template>
    </div>
    <search-dialog v-model:visible="searchDialogVisible" :type="searchType" />
    <salary-calculator />
    <screen-recorder />
    <login-dialog v-model:visible="loginDialogVisible" @loginSuccess="handleLoginSuccess" @registerSuccess="handleRegisterSuccess" />
    <change-password-dialog v-model:visible="changePasswordDialogVisible" @success="handleChangePasswordSuccess" />
  </a-config-provider>
</template>

<script setup>
import zhCN from 'ant-design-vue/es/locale/zh_CN'
import { useBookmarkStore } from './stores/bookmark'
import { useUserStore } from './stores/user'
import { getImageUrl } from './utils/image'
import { ref, nextTick, onMounted, watch, onUnmounted, computed } from 'vue'
import {
  ToolOutlined,
  SettingOutlined,
  FileImageOutlined,
  GitlabOutlined,
  CalendarOutlined,
  ClockCircleOutlined,
  KeyOutlined,
  FileOutlined,
  VideoCameraOutlined,
  BarChartOutlined,
  EditOutlined,
  UserOutlined,
  LockOutlined,
  CoffeeOutlined,
  CodeOutlined,
  FileTextOutlined,
  BellOutlined,
  FolderOutlined
} from '@ant-design/icons-vue'
import { message, Modal } from 'ant-design-vue'
import { useRouter, useRoute } from 'vue-router'
import SearchDialog from './components/SearchDialog.vue'
import SalaryCalculator from './components/SalaryCalculator/index.vue'
import ScreenRecorder from './components/ScreenRecorder/index.vue'
import LoginDialog from './components/LoginDialog.vue'
import ChangePasswordDialog from './components/ChangePasswordDialog.vue'
import { verifyToken, refreshToken, getUnreadNotificationCount } from './utils/api.js'
import { getToken, removeToken, setToken } from './utils/auth.js'

// 检测是否为移动设备
const isMobileDevice = ref(false)

const checkDeviceType = () => {
  if (typeof window === 'undefined') {
    isMobileDevice.value = false
    return
  }
  isMobileDevice.value = /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) || window.innerWidth <= 768
}

// 监听窗口大小变化
const handleResize = () => {
  checkDeviceType()
}

const store = useBookmarkStore()
const userStore = useUserStore()
const storeReady = ref(false)
const router = useRouter()
const route = useRoute()

// 咖啡墙页面背景控制
const isCoffeeWallPage = ref(false)

const searchDialogVisible = ref(false)
const searchType = ref('baidu')
const loginDialogVisible = ref(false)
const changePasswordDialogVisible = ref(false)

// 消息通知相关
const unreadNotificationCount = ref(0)

// 全局主题配置
const themeConfig = {
  token: {
    colorPrimary: '#344767'
  }
}

const openIllustrationGallery = () => {
  router.push('/illustration-gallery')
}

const openXiaoBaWang = () => {
  router.push('/xiaobawang')
}

const openWhiteboard = () => {
  router.push('/whiteboard')
}

const openEcharts = () => {
  router.push('/echarts')
}

const openUserManagement = () => {
  router.push('/user-management')
}

const openArticles = () => {
  router.push('/articles')
}

const openCoffeeWall = () => {
  router.push('/coffee-wall')
}

const openFileStorage = () => {
  router.push('/file-storage')
}

const openFontManager = () => {
  router.push('/font-manager')
}

// 检查是否为管理员
const isAdmin = computed(() => {
  return userStore.isAuthenticated && userStore.user?.username === 'woaichitudouo'
})

const openLoginDialog = () => {
  loginDialogVisible.value = true
}

const openUserCenter = () => {
  if (userStore.isAuthenticated) {
    router.push(`/user/${userStore.user.userId}?view=profile`)
  }
}

const openMyArticles = () => {
  if (userStore.isAuthenticated) {
    router.push(`/user/${userStore.user.userId}?view=articles`)
  }
}

const openNotifications = () => {
  if (userStore.isAuthenticated) {
    router.push(`/user/${userStore.user.userId}?view=notifications`)
  }
}

// 获取未读消息数量
const fetchUnreadNotificationCount = async () => {
  if (!userStore.isAuthenticated) {
    unreadNotificationCount.value = 0
    return
  }

  try {
    const response = await getUnreadNotificationCount()
    unreadNotificationCount.value = response.data?.totalUnread || 0
  } catch (error) {
    console.error('获取未读消息数量失败:', error)
    unreadNotificationCount.value = 0
  }
}

const openChangePasswordDialog = () => {
  changePasswordDialogVisible.value = true
}

// 处理登出
const handleLogout = () => {
  Modal.confirm({
    title: '确认退出',
    content: '您确定要退出登录吗？',
    okText: '确定',
    cancelText: '取消',
    onOk: () => {
      userStore.logout()
      message.success('已退出登录')
    }
  })
}

// 处理登录成功
const handleLoginSuccess = (user) => {
  message.success(`欢迎回来，${user.username}！`)
  // 登录成功后可以选择性地验证一次token状态
  checkTokenValidity()
  // 获取未读消息数量
  fetchUnreadNotificationCount()
}

// 处理注册成功
const handleRegisterSuccess = (user) => {
  message.success(`注册成功，欢迎使用，${user.username}！`)
  // 注册成功后验证token状态
  checkTokenValidity()
  // 获取未读消息数量
  fetchUnreadNotificationCount()
}

// 处理修改密码成功
const handleChangePasswordSuccess = () => {
  changePasswordDialogVisible.value = false
}

// 快捷键处理函数
const keydownListener = (e) => {
  // 只在首页时才响应快捷键
  if (route.path !== '/') {
    return
  }

  // 如果有模态框打开，禁用快捷键
  if (loginDialogVisible.value || searchDialogVisible.value || store.isBookmarkModalOpen || store.isCategoryModalOpen || changePasswordDialogVisible.value) {
    return
  }

  // 如果搜索框聚焦，也禁用快捷键
  if (store.isSearchFocused) {
    return
  }

  // 没有按下其他修饰键
  const noModifiers = !e.ctrlKey && !e.altKey && !e.shiftKey && !e.metaKey

  if (e.key === '`' && noModifiers) {
    // 添加书签快捷键
    e.preventDefault()
    window.dispatchEvent(new CustomEvent('addBookmark'))
  } else if (e.key.toLowerCase() === 'b' && noModifiers) {
    // 打开百度搜索弹窗
    e.preventDefault()
    searchType.value = 'baidu'
    searchDialogVisible.value = true
  } else if (e.key.toLowerCase() === 'g' && noModifiers) {
    // 打开谷歌搜索弹窗
    e.preventDefault()
    searchType.value = 'google'
    searchDialogVisible.value = true
  }
}

// 使用 watch 监听相关状态的变化
watch(
  [() => store.isSearchFocused, () => loginDialogVisible.value, () => searchDialogVisible.value, () => store.isBookmarkModalOpen, () => store.isCategoryModalOpen, () => changePasswordDialogVisible.value],
  ([isSearchFocused, isLoginVisible, isSearchDialogVisible, isBookmarkModalOpen, isCategoryModalOpen, isChangePasswordVisible]) => {
    // 如果任何一个状态为true，移除事件监听器
    if (isSearchFocused || isLoginVisible || isSearchDialogVisible || isBookmarkModalOpen || isCategoryModalOpen || isChangePasswordVisible) {
      document.removeEventListener('keydown', keydownListener)
    } else {
      // 所有状态都为false时，添加事件监听器
      document.addEventListener('keydown', keydownListener)
    }
  }
)

// 处理全局登录事件
const handleGlobalLogin = () => {
  openLoginDialog()
}

// 监听路由变化，检查是否在咖啡墙页面
watch(
  () => route.path,
  (newPath) => {
    isCoffeeWallPage.value = newPath === '/coffee-wall'
  },
  { immediate: true }
)

// Token验证逻辑
const checkTokenValidity = () => {
  const token = getToken()

  // 如果没有token，直接返回
  if (!token) {
    return Promise.resolve()
  }

  // 验证token是否有效
  return verifyToken()
    .then((response) => {
      if (response.data && response.data.valid) {
        // Token有效，更新用户信息
        const { user } = response.data
        userStore.setUser({
          userId: user.userId,
          username: user.username,
          email: user.email || '',
          avatar: user.avatar || null
        })

        // 获取未读消息数量
        fetchUnreadNotificationCount()

        // 检查token是否即将过期（小于30分钟）
        const remainingTime = response.data.remainingTimeSeconds
        if (remainingTime && remainingTime < 1800) {
          // 30分钟 = 1800秒
          // 尝试刷新token
          return refreshToken()
            .then((refreshResponse) => {
              if (refreshResponse.data && refreshResponse.data.token) {
                // 保存新的token
                setToken(refreshResponse.data.token)
                console.log('Token已自动刷新')

                // 更新用户信息（包括头像）
                if (refreshResponse.data.user) {
                  userStore.setUser(refreshResponse.data.user)
                }
              }
            })
            .catch((refreshError) => {
              console.warn('Token刷新失败:', refreshError.message)
              // 刷新失败，提示用户重新登录
              message.warning('登录状态即将过期，请重新登录', 2)
            })
        }
      }
    })
    .catch((error) => {
      console.error('Token验证失败:', error.message)

      // Token无效，清除本地存储并退出登录状态
      removeToken()
      userStore.logout()

      // 根据错误类型给出不同提示
      if (error.message.includes('过期')) {
        message.warning('登录已过期，请重新登录')
      } else if (error.message.includes('无效')) {
        message.warning('登录状态无效，请重新登录')
      }
    })
}

// 页面可见性变化时检查token
const handleVisibilityChange = () => {
  if (!document.hidden && userStore.isAuthenticated) {
    // 页面变为可见且用户已登录时，检查token有效性
    checkTokenValidity()
  }
}

// 确保 store 数据已加载
onMounted(() => {
  // 初始检查设备类型
  checkDeviceType()
  // 添加resize事件监听
  window.addEventListener('resize', handleResize)

  // 首先检查token有效性
  checkTokenValidity()
    .then(() => {
      nextTick(() => {
        storeReady.value = true
        if (!store.isSearchFocused) {
          document.addEventListener('keydown', keydownListener)
        }
      })
    })
    .catch((error) => {
      console.error('Token检查失败:', error)
      nextTick(() => {
        storeReady.value = true
        if (!store.isSearchFocused) {
          document.addEventListener('keydown', keydownListener)
        }
      })
    })

  // 监听全局登录事件
  window.addEventListener('openLogin', handleGlobalLogin)

  // 监听页面可见性变化
  document.addEventListener('visibilitychange', handleVisibilityChange)
})

// 组件卸载时清理事件监听器
onUnmounted(() => {
  document.removeEventListener('keydown', keydownListener)
  window.removeEventListener('openLogin', handleGlobalLogin)
  document.removeEventListener('visibilitychange', handleVisibilityChange)
  // 移除resize事件监听
  window.removeEventListener('resize', handleResize)
})

// 定义菜单项数据
const toolMenuItems = [
  {
    key: 'vacation',
    label: '放假安排',
    icon: CalendarOutlined,
    action: () => router.push('/vacation')
  },
  {
    key: 'git-memo',
    label: 'Git 备忘录',
    icon: GitlabOutlined,
    action: () => router.push('/git-memo')
  },
  {
    key: 'code',
    label: '自定义代码',
    icon: SettingOutlined,
    action: () => router.push('/code-editor')
  },
  {
    key: 'image',
    label: '图片压缩',
    icon: FileImageOutlined,
    action: () => router.push('/image-compressor')
  },
  {
    key: 'color-converter',
    label: '颜色转换器',
    icon: SettingOutlined,
    action: () => router.push('/color-converter')
  },
  {
    key: 'qr-code-generator',
    label: '二维码生成器',
    icon: FileImageOutlined,
    action: () => router.push('/qr-code-generator')
  },
  {
    key: 'date-time-converter',
    label: '日期时间转换器',
    icon: CalendarOutlined,
    action: () => router.push('/date-time-converter')
  },
  {
    key: 'timer',
    label: '计时器',
    icon: ClockCircleOutlined,
    action: () => router.push('/timer')
  },
  {
    key: 'token-generator',
    label: 'Token 生成器',
    icon: KeyOutlined,
    action: () => router.push('/token-generator')
  },
  {
    key: 'base64-encoder',
    label: 'Base64 字符串编码/解码',
    icon: SettingOutlined,
    action: () => router.push('/base64-encoder')
  },
  {
    key: 'base64-file-converter',
    label: 'Base64 文件转换器',
    icon: FileOutlined,
    action: () => router.push('/base64-file-converter')
  },
  {
    key: 'keycode-info',
    label: 'Keycode 信息',
    icon: SettingOutlined,
    action: () => router.push('/keycode-info')
  },
  {
    key: 'lottery-generator',
    label: '双色球号码生成器',
    icon: FileOutlined,
    action: () => router.push('/lottery-generator')
  },
  {
    key: 'xiaobawang',
    label: '小霸王游戏机',
    icon: VideoCameraOutlined,
    action: () => router.push('/xiaobawang')
  }
]

// 修改工具点击处理函数
const handleToolClick = (key) => {
  const menuItem = toolMenuItems.find((item) => item.key === key)
  if (menuItem) {
    menuItem.action()
  }
}
</script>

<style scoped>
@import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap');
@import url('https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css');

:deep(.ant-btn-primary) {
  box-shadow: none !important;
}

.footer {
  text-align: center;
  padding: 6px 0;
  font-size: 14px;
  color: #666;
}
.footer a {
  color: #666;
}
.layout {
  min-height: 100vh;
  height: 100vh;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.header {
  display: flex;
  align-items: center;
  padding: 0 24px;
  background: #fff;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
  height: 64px;
  flex-shrink: 0;
}

.logo {
  margin-right: 24px;
  font-size: 18px;
  font-weight: bold;
  cursor: pointer;
}

.content {
  background: #f0f2f5;
  flex: 1;
  overflow: hidden;
  box-sizing: border-box;
  position: relative;
}

.header-actions {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-left: auto;
}

.header-actions .ant-btn-link {
  color: #67748e !important;
}

.header-actions .ant-btn-link:hover {
  color: #67748e !important;
}

:deep(.ant-dropdown-trigger) {
  margin-right: 8px;
}

/* 咖啡墙页面背景样式 */
.header.coffee-wall-bg,
.footer.coffee-wall-bg {
  background-image: url('@/assets/wall.jpg');
  background-size: cover;
  background-position: center;
  background-repeat: no-repeat;
  color: #f4e4bc;
  position: relative;
}

.header.coffee-wall-bg::before,
.footer.coffee-wall-bg::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.3);
  z-index: 1;
}

.header.coffee-wall-bg > *,
.footer.coffee-wall-bg > * {
  position: relative;
  z-index: 2;
}

.header.coffee-wall-bg .logo {
  color: #f4e4bc;
  text-shadow: 1px 1px 2px rgba(0, 0, 0, 0.5);
}

.header.coffee-wall-bg .header-actions .ant-btn-link {
  color: #f4e4bc !important;
  text-shadow: 1px 1px 2px rgba(0, 0, 0, 0.5);
}

.header.coffee-wall-bg .header-actions .ant-btn-link:hover {
  color: #d4af37 !important;
}

.footer.coffee-wall-bg {
  color: #f4e4bc;
  text-shadow: 1px 1px 2px rgba(0, 0, 0, 0.5);
}

.footer.coffee-wall-bg a {
  color: #d4af37;
  text-shadow: 1px 1px 2px rgba(0, 0, 0, 0.5);
}

/* 移动端提示样式 */
.mobile-warning {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: #fff;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  z-index: 9999;
  padding: 20px;
  text-align: center;
}

.mobile-warning h2 {
  color: #344767;
  margin-bottom: 10px;
  font-size: 24px;
}

.mobile-warning p {
  color: #67748e;
  font-size: 16px;
}
</style>
